package com.demo.htmltopng.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtils {

    final static int TIMEOUT = 1000;

    final static int TIMEOUT_MSEC = 5 * 1000;

    public static String doPost(String url, Map<String, String> paramMap) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            // 创建参数列表
            if (paramMap != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, String> param : paramMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }

            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
        }

        return resultString;
    }


    private static RequestConfig builderRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(TIMEOUT_MSEC)
                .setConnectionRequestTimeout(TIMEOUT_MSEC)
                .setSocketTimeout(TIMEOUT_MSEC).build();
    }


    public static JSONObject doURL(String temp) throws IOException {
        // 我们需要进行请求的地址：

        JSONObject jsonObject1 = new JSONObject();
        //String temp = "https://static.wego-smart.com/xjw-work/1452939401401503744.jpg?x-oss-process=image/info";
        try {
            // 1.URL类封装了大量复杂的实现细节，这里将一个字符串构造成一个URL对象
            URL url = new URL(temp);
            // 2.获取HttpURRLConnection对象
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 3.调用connect方法连接远程资源
            connection.connect();
            // 4.访问资源数据，使用getInputStream方法获取一个输入流用以读取信息
            BufferedReader bReader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "UTF-8"));

            // 对数据进行访问
            String line = null;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bReader.readLine()) != null) {
                stringBuilder.append(line);
            }

            // 关闭流
            bReader.close();
            // 关闭链接
            connection.disconnect();
            // 打印获取的结果
            jsonObject1 = JSONObject.parseObject(stringBuilder.toString(), JSONObject.class);
            //System.out.println(stringBuilder.toString());
            //  JSONObject jsonObject2 = JSONObject.parseObject(jsonObject1.get("ImageHeight").toString(), JSONObject.class);
            //  String value = (String) jsonObject2.get("value");

            // JSONObject jsonObject3 = JSONObject.parseObject(jsonObject1.get("ImageWidth").toString(), JSONObject.class);
            // String value1 = (String) jsonObject3.get("value");
            // System.out.println("高: "+value);
            //  System.out.println("宽: "+value1);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return jsonObject1;
    }

    /*public BufferedImage getUrlImage(String url) {
        byte[] bytes = HttpsUtils.getBytes(url);
        InputStream buffin = new ByteArrayInputStream(bytes,0,bytes.length);
        BufferedImage img = null;
        try {
            img = ImageIO.read(buffin);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return img;
    }*/

    public static InputStream doURLS(String temp) throws IOException {
        // 我们需要进行请求的地址：

        InputStream strToStream = null;
        //String temp = "https://static.wego-smart.com/xjw-work/1452939401401503744.jpg?x-oss-process=image/info";
        try {
            // 1.URL类封装了大量复杂的实现细节，这里将一个字符串构造成一个URL对象
            URL url = new URL(temp);
            // 2.获取HttpURRLConnection对象
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 3.调用connect方法连接远程资源
            connection.connect();
            // 4.访问资源数据，使用getInputStream方法获取一个输入流用以读取信息
            BufferedReader bReader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "UTF-8"));

            // 对数据进行访问
            String line = null;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bReader.readLine()) != null) {
                stringBuilder.append(line);
            }

            // 关闭流
            bReader.close();
            // 关闭链接
            connection.disconnect();
            // 打印获取的结果
             strToStream = getStrToStream(stringBuilder.toString());
            //System.out.println(stringBuilder.toString());
            //  JSONObject jsonObject2 = JSONObject.parseObject(jsonObject1.get("ImageHeight").toString(), JSONObject.class);
            //  String value = (String) jsonObject2.get("value");

            // JSONObject jsonObject3 = JSONObject.parseObject(jsonObject1.get("ImageWidth").toString(), JSONObject.class);
            // String value1 = (String) jsonObject3.get("value");
            // System.out.println("高: "+value);
            //  System.out.println("宽: "+value1);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return strToStream;
    }


    public static InputStream getStringStream(String str) throws Exception {
        if (str != null && !str.trim().equals("")) {
            ByteArrayInputStream stringStream = new ByteArrayInputStream(str.getBytes());
            return stringStream;
        }
        return null;
    }

    public static String getStreamString(InputStream tInputStream) throws Exception {
        if (tInputStream != null) {
            BufferedReader tBufferedReader = new BufferedReader(new InputStreamReader(tInputStream));
            StringBuffer tStringBuffer = new StringBuffer();
            String sTempOneLine = new String("");
            while ((sTempOneLine = tBufferedReader.readLine()) != null) {
                tStringBuffer.append(sTempOneLine);
            }
            return tStringBuffer.toString();
        }
        return null;
    }

    public static InputStream getStrToStream(String sInputString) {
        if (sInputString != null && !sInputString.trim().equals("")) {
            try {
                ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(sInputString.getBytes());
                return tInputStringStream;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 从HTTP请求中获取输入流
     *
     * @param requestUrl
     * @param
     * @return
     * @throws IOException
     */
    public static InputStream doHttpGetRequest(String requestUrl) throws IOException {
        HttpURLConnection httpConnection = null;
        try {
// String strTemp=null;
            URL url = new URL(requestUrl);
            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setDoOutput(true);
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();
            InputStream inputStream = httpConnection.getInputStream();
            return readInputStreamAsString(inputStream,
                    httpConnection.getContentLength());
        } finally {
            if (httpConnection != null) {
                httpConnection.disconnect();
            }
        }
    }


    /**
     * 从输入流中读取数据
     *
     * @param
     * @return
     * @throws IOException
     */
    public static InputStream readInputStreamAsString(InputStream inputStream,
                                                 int length) throws IOException {
        if (inputStream != null) {
            byte[] streamBytes = new byte[length];
            inputStream.read(streamBytes);
            return inputStream ;
        }
        return null;
    }




    //调用放

    /**
     * 获取封装得MultipartFile
     *
     * @param inputStream inputStream
     * @param fileName    fileName
     * @return MultipartFile
     */
    public static MultipartFile getMultipartFile(InputStream inputStream, String fileName) {
        FileItem fileItem = createFileItem(inputStream, fileName);
        //CommonsMultipartFile是feign对multipartFile的封装，但是要FileItem类对象
        return new CommonsMultipartFile(fileItem);
    }


    /**
     * FileItem类对象创建
     *
     * @param inputStream inputStream
     * @param fileName    fileName
     * @return FileItem
     */
    public static FileItem createFileItem(InputStream inputStream, String fileName) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        String textFieldName = "file";
        FileItem item = factory.createItem(textFieldName, MediaType.MULTIPART_FORM_DATA_VALUE, true, fileName);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        OutputStream os = null;
        //使用输出流输出输入流的字节
        try {
            os = item.getOutputStream();
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            inputStream.close();
        } catch (IOException e) {
           // log.error("Stream copy exception", e);
            throw new IllegalArgumentException("文件上传失败");
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                   // log.error("Stream close exception", e);

                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                  //  log.error("Stream close exception", e);
                }
            }
        }

        return item;
    }


}